package com.apes.fn.rpt.settle.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.business.insurance.modle.InsuranceOrder;
import com.apes.fn.business.insurance.repository.InsuranceOrderRepository;
import com.apes.fn.fico.debitnote.model.BusinessDebitNote;
import com.apes.fn.fico.debitnote.repository.BusinessDebitNoteRepository;
import com.apes.fn.fico.expense.ExpenseItem;
import com.apes.fn.fico.expense.ExpenseItemRepository;
import com.apes.fn.rpt.settle.model.ExpenditureSummary;
import com.apes.fn.rpt.settle.repository.ExpenditureRepository;
import com.apes.fn.rpt.settle.repository.SummaryDao;
import com.apes.fn.scm.merchant.account.model.MerchantAccountSettlement;
import com.apes.fn.scm.merchant.account.model.SettlementBusinessDebitItem;
import com.apes.fn.scm.merchant.account.model.SettlementExpenseItem;
import com.apes.fn.scm.merchant.account.repository.AccountSettlementRepository;
import com.apes.fn.scm.merchant.account.repository.SettlementBusinessDebitRepository;
import com.apes.fn.scm.merchant.account.repository.SettlementExpenseItemRepository;
import com.apes.fn.scm.merchant.settlement.model.MerchantSettlement;
import com.apes.fn.scm.merchant.settlement.repository.MerchantSettlementDao;
import com.apes.fn.scm.merchant.settlement.service.FeeRateService;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.Arith;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author pengyb
 */
@Service("expenditureSummaryService")
public class ExpenditureSummaryService extends DomainService {
    @Autowired
    private EnumerationRepository enumerationRepository;

    @Autowired
    private SummaryDao summaryDao;

    @Autowired
    private PartyRoleRepository partyRoleRepository;

    @Autowired
    private MerchantSettlementDao merchantSettlementDao;

    @Autowired
    private FeeRateService feeRateService;
    @Autowired
    private ExpenditureRepository expenditureRepository;

    @Autowired
    private IncomeSummaryService incomeSummaryService;

    @Autowired
    private InsuranceOrderRepository insuranceOrderRepository;

    /**
     * 生成报表
     *
     * @param request
     */
    private void generate(SimpleRequest request) {
        //获取日期
        Date date = DateUtil.dateToDate(request.getJO().getDate("taskDate"), DateUtil.SHOW_DATE_FORMAT);
        //获取营业收入枚举
        List<Enumeration> summaries = enumerationRepository.findAll(JpaDsl.toCriteriaByEq("type.id", "expenditureSummary", "valid", 1));
        summaryDao.queryExpenditure(date, date).forEach(result -> {
            if (result.get("COMPANY_ID") == null) return;
            PartyRole company = partyRoleRepository.findOne((String) result.get("COMPANY_ID"));
            buildExpenditureSummary(summaries, result, company, date);

        });

    }


    /**
     * 批量生成
     *
     * @param request
     */
    public void batchGenerate(SimpleRequest request) {
        JSONObject requestJO = request.getJO();
        Date startDate = DateUtil.dateToDate(requestJO.getDate("startDate"), DateUtil.SHOW_DATE_FORMAT);
        Date endDate = DateUtil.dateToDate(requestJO.getDate("endDate"), DateUtil.SHOW_DATE_FORMAT);
        //获取营业收入枚举
        List<Enumeration> summaries = enumerationRepository.findAll(JpaDsl.toCriteriaByEq("type.id", "expenditureSummary", "valid", 1));

        summaryDao.queryExpenditure(startDate, endDate).forEach(result -> {
            PartyRole company = partyRoleRepository.findOne((String) result.get("COMPANY_ID"));
            Date statisticsDate = DateUtil.parse(result.get("DATE_OF_STATISTICS").toString());
            buildExpenditureSummary(summaries, result, company, statisticsDate);

        });
    }

    /**
     * 构建报表
     *
     * @param summaries
     * @param result
     * @param company
     * @param statisticsDate
     */
    private void buildExpenditureSummary(List<Enumeration> summaries, Map result, PartyRole company, Date statisticsDate) {
        summaries.forEach(enumeration -> {
            if (result.get(enumeration.getCode()) == null) return;
            Double amount = Double.valueOf(result.get(enumeration.getCode()).toString());
            ExpenditureSummary expenditureSummary = expenditureRepository.findOne(
                    JpaDsl.toCriteriaByEq("company.id", company.getId(), "statisticsDate", statisticsDate, "expenditureType.id", enumeration.getId())).orElse(new ExpenditureSummary());
            expenditureSummary.setExpenditureType(enumeration);
            expenditureSummary.setCompany(company);
            expenditureSummary.setAmount(amount);
            expenditureSummary.setStatisticsDate(statisticsDate);
            expenditureRepository.saveAndFlush(expenditureSummary);
        });
    }

    /**
     * 查询供应链管理费明细
     *
     * @param request
     * @return
     */
    public JSONObject findManagementFee(SimpleRequest request) throws ParseException {
        JSONObject requestJO = request.getJO();
        JSONObject parseRequest = incomeSummaryService.parseRequest(request, requestJO);
        //取结果集
        List<Map> resultList = merchantSettlementDao.findManagementFee(parseRequest.getString("merchantId"),
                parseRequest.getDate("reconcileBeginDate"), parseRequest.getDate("reconcileEndDate"), parseRequest.getIntValue("page"), parseRequest.getIntValue("size"));
        Object count = merchantSettlementDao.findManagementFeCount(parseRequest.getString("merchantId"), parseRequest.getDate("reconcileBeginDate"), parseRequest.getDate("reconcileEndDate"));
        JSONObject object = new JSONObject();
        object.put("content", resultList);
        object.put("total", count);
        object.put("pages", count);
        return object;
    }

    /**
     * 获取代销货款凭证信息
     *
     * @param request
     * @return
     */
    public JSONObject findConsign(SimpleRequest request) {
        JSONObject requestJO = request.getJO();
        JSONObject parseRequest = incomeSummaryService.parseRequest(request, requestJO);
        //取结果集
        List<Map> resultList = merchantSettlementDao.findConsignVoucherCosts(parseRequest.getString("merchantId"),
                parseRequest.getDate("reconcileBeginDate"), parseRequest.getDate("reconcileEndDate"), parseRequest.getIntValue("page"), parseRequest.getIntValue("size"));
        Object costsCount = merchantSettlementDao.findConsignVoucherCostsCount(parseRequest.getString("merchantId"),
                parseRequest.getDate("reconcileBeginDate"), parseRequest.getDate("reconcileEndDate"));
        JSONObject object = new JSONObject();
        object.put("content", resultList);
        object.put("total", costsCount);
        object.put("pages", costsCount);
        return object;
    }

    /**
     * 获取经销货款凭证信息
     *
     * @param request
     * @return
     */
    public JSONObject findOwn(SimpleRequest request) {
        JSONObject requestJO = request.getJO();
        JSONObject parseRequest = incomeSummaryService.parseRequest(request, requestJO);
        //取结果集
        List<Map> resultList = merchantSettlementDao.findOwnVoucherCosts(parseRequest.getString("merchantId"),
                parseRequest.getDate("reconcileBeginDate"), parseRequest.getDate("reconcileEndDate"), parseRequest.getIntValue("page"), parseRequest.getIntValue("size"));
        Object costsCount = merchantSettlementDao.findOwnVoucherCostsCount(parseRequest.getString("merchantId"),
                parseRequest.getDate("reconcileBeginDate"), parseRequest.getDate("reconcileEndDate"));
        JSONObject object = new JSONObject();
        object.put("content", resultList);
        object.put("total", costsCount);
        object.put("pages", costsCount);
        return object;
    }

    /**
     * 获取代销货款账单信息
     *
     * @param request
     * @return
     */
    public JSONObject findInvoiceConsign(SimpleRequest request) {
        JSONObject requestJO = request.getJO();
        JSONObject parseRequest = incomeSummaryService.parseRequest(request, requestJO);
        //取结果集
        List<Map> resultList = merchantSettlementDao.findOwnInvoiceCosts(parseRequest.getString("merchantId"),
                parseRequest.getDate("reconcileBeginDate"), parseRequest.getDate("reconcileEndDate"),
                "IM_CONSIGN", parseRequest.getIntValue("page"), parseRequest.getIntValue("size"));
        List<Map> costsCount = merchantSettlementDao.findOwnInvoiceCostsCount(parseRequest.getString("merchantId"),
                parseRequest.getDate("reconcileBeginDate"), parseRequest.getDate("reconcileEndDate"), "IM_CONSIGN");

        JSONObject object = new JSONObject();
        object.put("content", resultList);
        object.put("total", costsCount.get(0).get("COUNT"));
        object.put("pages", costsCount);
        object.put("footer", Arrays.asList(MapUtil.mapper(
                "PRICE_SUBTOTAL", costsCount.get(0).get("PRICE_SUBTOTAL"),
                "QTY", costsCount.get(0).get("QTY"),
                "PRICE_UNIT", costsCount.get(0).get("PRICE_UNIT"),
                "DISCOUNT", costsCount.get(0).get("DISCOUNT")
        )));
        return object;
    }

    /**
     * 获取经销货款账单信息
     *
     * @param request
     * @return
     */
    public JSONObject findInvoiceOwn(SimpleRequest request) {
        JSONObject requestJO = request.getJO();
        JSONObject parseRequest = incomeSummaryService.parseRequest(request, requestJO);
        //取结果集
        List<Map> resultList = merchantSettlementDao.findOwnInvoiceCosts(parseRequest.getString("merchantId"),
                parseRequest.getDate("reconcileBeginDate"), parseRequest.getDate("reconcileEndDate"), "IM_OWN", parseRequest.getIntValue("page"), parseRequest.getIntValue("size"));
        List<Map> costsCount = merchantSettlementDao.findOwnInvoiceCostsCount(parseRequest.getString("merchantId"),
                parseRequest.getDate("reconcileBeginDate"), parseRequest.getDate("reconcileEndDate"), "IM_OWN");

        JSONObject object = new JSONObject();
        object.put("content", resultList);
        object.put("total", costsCount.get(0).get("COUNT"));
        object.put("pages", costsCount);
        object.put("footer", Arrays.asList(MapUtil.mapper(
                "PRICE_SUBTOTAL", costsCount.get(0).get("PRICE_SUBTOTAL"),
                "QTY", costsCount.get(0).get("QTY"),
                "PRICE_UNIT", costsCount.get(0).get("PRICE_UNIT"),
                "DISCOUNT", costsCount.get(0).get("DISCOUNT")
        )));
        return object;
    }


    /**
     * 三方平台引流成本
     *
     * @param request
     * @return
     */
    public JSONObject findDrainageCost(SimpleRequest request) {
        JSONObject requestJO = request.getJO();
        JSONObject parseRequest = incomeSummaryService.parseRequest(request, requestJO);
        //取结果集
        List<Map> resultList = summaryDao.findDrainageCost(parseRequest.getString("merchantId"),
                parseRequest.getDate("reconcileBeginDate"), parseRequest.getDate("reconcileEndDate"), parseRequest.getIntValue("page"), parseRequest.getIntValue("size"));
        Object costsCount = summaryDao.findDrainageCostCount(parseRequest.getString("merchantId"),
                parseRequest.getDate("reconcileBeginDate"), parseRequest.getDate("reconcileEndDate"));
        JSONObject object = new JSONObject();
        object.put("content", resultList);
        object.put("total", costsCount);
        object.put("pages", costsCount);
        return object;
    }


    /**
     * 获取车险销售额费用明细
     *
     * @param request
     * @return
     */
    public Page<InsuranceOrder> findInsuranceManagementFee(SimpleRequest request) {
        JSONObject requestJO = request.getJO();
        JSONObject parseRequest = incomeSummaryService.parseRequest(request, requestJO);
        Page<InsuranceOrder> insuranceOrders = insuranceOrderRepository.findByCompany(parseRequest.getString("merchantId"),
                parseRequest.getDate("reconcileBeginDate"), parseRequest.getDate("reconcileEndDate"), PageRequest.of(parseRequest.getInteger("page") - 1, parseRequest.getInteger("size")));
        return insuranceOrders;
    }

    /**
     * 获取费用明细
     *
     * @param request
     * @return
     */
    public JSONObject findExpense(SimpleRequest request) {
        JSONObject requestJO = request.getJO();
        JSONObject object = new JSONObject();
        JSONObject parseRequest = incomeSummaryService.parseRequest(request, requestJO);
        List<Map> list = new ArrayList<>();
        if (requestJO.containsKey("data") && requestJO.getJSONObject("data").containsKey("id") && requestJO.getJSONObject("data").getString("id") != null) {
            String id = requestJO.getJSONObject("data").getString("id");
            SpringManager.getBean(AccountSettlementRepository.class).findOne(id).getExpenseItems().forEach(merchantExpenseItem -> {
                JSONObject result = new JSONObject();
                result.put("id", merchantExpenseItem.getIncomeItem().getIncome().getId());
                result.put("name", merchantExpenseItem.getIncomeItem().getIncomeType().getName());
                result.put("tenant", merchantExpenseItem.getIncomeItem().getIncome().getCompany().getName());
                result.put("amount", merchantExpenseItem.getIncomeItem().getIncomeAmount());
                result.put("withholdingAmount", merchantExpenseItem.getIncomeItem().getFreezeAmount());
                result.put("amountDeducted", merchantExpenseItem.getIncomeItem().getRecoveryAmount());
                result.put("note", merchantExpenseItem.getIncomeItem().getNote());
                result.put("periodStart", Objects.isNull(merchantExpenseItem.getIncomeItem().getStartDate()) ? null : DateUtil.format(merchantExpenseItem.getIncomeItem().getStartDate(), "yyyy-MM-dd"));
                result.put("periodEnd", Objects.isNull(merchantExpenseItem.getIncomeItem().getEndDate()) ? null : DateUtil.format(merchantExpenseItem.getIncomeItem().getEndDate(), "yyyy-MM-dd"));
                result.put("creator", Objects.isNull(merchantExpenseItem.getIncomeItem().getIncome().getCreator()) ? null : SpringManager.getBean(PartyRoleRepository.class).findOne(merchantExpenseItem.getIncomeItem().getIncome().getCreator()).getName());
                result.put("origin", merchantExpenseItem.getIncomeItem().getIncome().getOrigin());
                result.put("source", merchantExpenseItem.getIncomeItem().getIncome().getSource());
                result.put("createDate", Objects.isNull(merchantExpenseItem.getIncomeItem().getCreateDate()) ? null : DateUtil.format(merchantExpenseItem.getIncomeItem().getStartDate(), "yyyy-MM-dd"));
                result.put("settlePolicy", merchantExpenseItem.getIncomeItem().getIncome().getSourceBusinessKey());
                list.add(result);
            });
            object.put("content", list);
            return object;

        }
        SpringManager.getBean(ExpenseItemRepository.class).findAllByExpenseCompany(parseRequest.getString("merchantId"),
                parseRequest.getDate("reconcileBeginDate"), parseRequest.getDate("reconcileEndDate")).forEach(expenseItem -> {
            JSONObject result = new JSONObject();
            result.put("id", expenseItem.getExpense().getId());
            result.put("tenant", expenseItem.getCompany().getName());
            result.put("name", expenseItem.getExpenseType().getName());
            result.put("amount", expenseItem.getAmount());
            result.put("withholdingAmount", expenseItem.getWithholdingAmount());
            result.put("amountDeducted", expenseItem.getAmountDeducted());
            result.put("note", expenseItem.getRemark());
            result.put("annex", expenseItem.getAnnex());
            result.put("periodStart", Objects.isNull(expenseItem.getPeriodStart()) ? null : DateUtil.format(expenseItem.getPeriodStart(), "yyyy-MM-dd"));
            result.put("periodEnd", Objects.isNull(expenseItem.getPeriodEnd()) ? null : DateUtil.format(expenseItem.getPeriodEnd(), "yyyy-MM-dd"));
            result.put("creator", Objects.isNull(expenseItem.getExpense().getCreator()) ? null : SpringManager.getBean(PartyRoleRepository.class).findOne(expenseItem.getExpense().getCreator()).getName());
            result.put("origin", expenseItem.getOrigin());
            result.put("source", expenseItem.getSource());
            result.put("createDate", Objects.isNull(expenseItem.getCreateDate()) ? null : DateUtil.format(expenseItem.getPeriodStart(), "yyyy-MM-dd"));
            result.put("settlePolicy", expenseItem.getSettlePolicy());
            list.add(result);
        });
        object.put("content", list);
        return object;
    }




    /**
     * 获取定损管理费明细
     *
     * @param request
     * @return
     */
    public JSONObject findQuotationExpense(SimpleRequest request) {
        JSONObject requestJO = request.getJO();
        JSONObject parseRequest = incomeSummaryService.parseRequest(request, requestJO);
        List<Map> resultList = merchantSettlementDao.findQuotationExpense(parseRequest.getString("merchantId"),
                parseRequest.getDate("reconcileBeginDate"), parseRequest.getDate("reconcileEndDate"), parseRequest.getIntValue("page"), parseRequest.getIntValue("size"));
        Object count = merchantSettlementDao.findQuotationExpenseCount(parseRequest.getString("merchantId"),
                parseRequest.getDate("reconcileBeginDate"), parseRequest.getDate("reconcileEndDate"));
        JSONObject object = new JSONObject();
        object.put("content", resultList);
        object.put("total", count);
        object.put("pages", count);
        return object;
    }

    /**
     * 对账单2.0平台费用
     *
     * @param request
     * @return
     */
    public JSONObject costPlatform(SimpleRequest request) {
        JSONObject requestJO = request.getJO();
        JSONObject parseRequest = incomeSummaryService.parseRequest(request, requestJO);
        //取结果集
        List<Map> resultList = merchantSettlementDao.costPlatform(parseRequest.getString("id"),
                parseRequest.getIntValue("page"), parseRequest.getIntValue("size"));
        Object costsCount = merchantSettlementDao.costPlatformCount(parseRequest.getString("id"));
        JSONObject object = new JSONObject();
        object.put("content", resultList);
        object.put("total", costsCount);
        object.put("pages", costsCount);
        return object;
    }

    /**
     * 获取借支明细
     *
     * @param request
     * @return
     */
    public Page<BusinessDebitNote> findBusiness(SimpleRequest request) {
        JSONObject requestJO = request.getJO();
        JSONObject parseRequest = incomeSummaryService.parseRequest(request, requestJO);
        if (requestJO.containsKey("data") && requestJO.getJSONObject("data").containsKey("id") && requestJO.getJSONObject("data").getString("id") != null) {
            String id = requestJO.getJSONObject("data").getString("id");
            return SpringManager.getBean(SettlementBusinessDebitRepository.class).findAllByMerchantSettlementId(id, PageRequest.of(parseRequest.getInteger("page") - 1, parseRequest.getInteger("size")));
        }
        Page<BusinessDebitNote> businessDebitNotes = SpringManager.getBean(BusinessDebitNoteRepository.class).findAllByFnCustomerId(parseRequest.getString("merchantId"),
                parseRequest.getDate("reconcileBeginDate"), parseRequest.getDate("reconcileEndDate"), PageRequest.of(parseRequest.getInteger("page") - 1, parseRequest.getInteger("size")));
        return businessDebitNotes;
    }

    /**
     * 获取借支明细
     *
     * @param request
     * @return
     */
    public JSONObject findBusinessDebitNote(SimpleRequest request) {
        JSONObject requestJO = request.getJO();
        JSONObject parseRequest = incomeSummaryService.parseRequest(request, requestJO);
        //取结果集
        List<Map> resultList = merchantSettlementDao.businessform(parseRequest.getString("id"),
                parseRequest.getIntValue("page"), parseRequest.getIntValue("size"));
        Object costsCount = merchantSettlementDao.businessformCount(parseRequest.getString("id"));
        JSONObject object = new JSONObject();
        object.put("content", resultList);
        object.put("total", costsCount);
        object.put("pages", costsCount);
        return object;
    }

    /**
     * 营业支出平台费用
     *
     * @param request
     * @return
     */
    public Map costPlatform1(SimpleRequest request) throws ParseException {
        JSONObject param = this.checkRequest(request);
        JSONArray payment = merchantSettlementDao.costPlatform1(param);
        //取结果集
        payment.forEach(pay -> {
            JSONObject jsonObject = (JSONObject) pay;
            if (param.get("DATE_OF_STATISTICS") != null && param.get("DATE_APPROVE") == null) {
                jsonObject.put("DATE_OF_STATISTICS", param.get("DATE_OF_STATISTICS"));
            }
            if (param.get("DATE_APPROVE") != null && param.get("DATE_OF_STATISTICS") != null) {
                try {
                    new SimpleDateFormat("yyyy-MM-dd").parse((String) param.get("DATE_APPROVE"));
                    jsonObject.put("DATE_APPROVE", param.get("DATE_APPROVE"));

                } catch (Exception e) {
                    jsonObject.put("DATE_OF_STATISTICS", param.get("DATE_OF_STATISTICS"));
                }
            }
            jsonObject.put("DATE_APPROVE", param.get("DATE_APPROVE"));
            jsonObject.put("COMPANY_ID", param.get("COMPANY_ID"));
            jsonObject.put("DATE_OF_STATISTICS", param.get("DATE_OF_STATISTICS"));

        });
        return packageReturnArray(payment);
    }

    /***
     * 包装返回数据
     */
    private Map packageReturnArray(JSONArray array) {
        int size = array.size();
        return MapUtil.mapper(
                "content", array,
                "total", size,
                "size", size
        );
    }

    /**
     * 解析前端参数
     *
     * @param request
     * @return
     */
    public JSONObject checkRequest(SimpleRequest request) {
        JSONObject condition = (JSONObject) request.get("condition");
        List<Map> filters = (List<Map>) condition.get("filters");
        JSONObject model = new JSONObject();
        filters.forEach(filter -> {
            model.put((String) filter.get("field"), filter.get("value"));
        });
        return model;
    }

    /**
     * 对账单平台费用
     *
     * @param request
     * @return
     */

    public JSONObject merchantCostPlatform(SimpleRequest request) throws ParseException {
        JSONObject requestJO = request.get("data");

        JSONArray tableHeader = new JSONArray();//拼接表头
        tableHeader.add(MapUtil.mapper("field", "ID", "headerName", "单号", "width", 100));
        tableHeader.add(MapUtil.mapper("field", "INCOME_TYPE_NAME", "headerName", "费用类型", "width", 150));
        tableHeader.add(MapUtil.mapper("field", "CAR_LICENSE", "headerName", "车牌", "width", 150));
        tableHeader.add(MapUtil.mapper("field", "AMOUNT", "headerName", "金额", "width", 100, "sum", true, "valueFormatter", "currency"));
        tableHeader.add(MapUtil.mapper("field", "RECOVERY_AMOUNT", "headerName", "往期已扣收", "width", 100, "sum", true, "valueFormatter", "currency"));
        tableHeader.add(MapUtil.mapper("field", "SETTLEMENT_AMOUNT", "headerName", "本期扣收", "width", 100, "sum", true, "valueFormatter", "currency"));
        tableHeader.add(MapUtil.mapper("field", "FREEZE_AMOUNT", "headerName", "扣收后结余", "width", 100, "sum", true, "valueFormatter", "currency"));
        tableHeader.add(MapUtil.mapper("field", "START_DATE", "headerName", "费用期间起", "width", 100));
        tableHeader.add(MapUtil.mapper("field", "END_DATE", "headerName", "费用期间止", "width", 100));
        tableHeader.add(MapUtil.mapper("field", "NOTE", "headerName", "备注", "width", 100));
        tableHeader.add(MapUtil.mapper("field", "SOURCE_BUSINESS_TYPE", "headerName", "上游单据", "width", 100));
        tableHeader.add(MapUtil.mapper("field", "SOURCE", "headerName", "上游单号", "width", 100));
        tableHeader.add(MapUtil.mapper("field", "CREATOR", "headerName", "创建人", "width", 100));
        tableHeader.add(MapUtil.mapper("field", "CREATE_DATE", "headerName", "创建时间", "width", 100));
        tableHeader.add(MapUtil.mapper("field", "SOURCE_BUSINESS_KEY", "headerName", "源单据", "width", 90));
        Map SOURCE = MapUtil.mapper("field", "SOURCE",
                "callback", "return {'IDS': data.SOURCE};",
                "headerName", "来源单号", "width", 90, "cellRenderer", "dialogButton", "buttonList", "[{'id':'search','name':'','hide':'false','disabled':'false'," +
                        "'action': 'link','link':'true','api': \'data.SOURCE_BUSINESS_TYPE == `平台定损费用` ? `report/fn.Quotation.expense`: `report/fn.expense.query`\', " +
                        "'config':{'OAInterface':false,'api': \'data.SOURCE_BUSINESS_TYPE == `平台定损费用` ? `fnQuotationExpense.query`: `fnExpense.query`\'}}]");
        tableHeader.add(SOURCE);

        List<Map> resultArray = merchantSettlementDao.merchantCostPlatform(requestJO.getJSONObject("node").get("ID").toString(),
                requestJO.getJSONObject("node").get("NAME").toString());

        JSONObject result = new JSONObject();
        result.put("tableHeader", tableHeader);
        result.put("content", resultArray);
        result.put("total", resultArray.size());
        result.put("footer", Arrays.asList(MapUtil.mapper(
                "RECOVERY_AMOUNT", resultArray.stream().map(x -> Double.valueOf(x.get("RECOVERY_AMOUNT").toString())).reduce(Arith::add).orElse(0.0),
                "SETTLEMENT_AMOUNT", resultArray.stream().map(x -> Double.valueOf(x.get("SETTLEMENT_AMOUNT").toString())).reduce(Arith::add).orElse(0.0),
                "AMOUNT", resultArray.stream().map(x -> Double.valueOf(x.get("AMOUNT").toString())).reduce(Arith::add).orElse(0.0),
                "FREEZE_AMOUNT", resultArray.stream().map(x -> Double.valueOf(x.get("FREEZE_AMOUNT").toString())).reduce(Arith::add).orElse(0.0)
        )));
        return result;
    }

    /**
     * 营业支出平台费用二级查询
     *
     * @param request
     * @return
     * @throws ParseException
     */
    public JSONObject merchantCostPlatform1(SimpleRequest request) throws ParseException {
        JSONArray tableHeader = new JSONArray();//拼接表头
        tableHeader.add(MapUtil.mapper("field", "ID", "headerName", "单号", "width", 100));
        tableHeader.add(MapUtil.mapper("field", "INCOME_TYPE_NAME", "headerName", "费用类型", "width", 150));
        tableHeader.add(MapUtil.mapper("field", "AMOUNT", "headerName", "金额", "width", 100, "sum", true, "valueFormatter", "currency"));
        tableHeader.add(MapUtil.mapper("field", "RECOVERY_AMOUNT", "headerName", "往期已扣收", "width", 100, "sum", true, "valueFormatter", "currency"));
        tableHeader.add(MapUtil.mapper("field", "FREEZE_AMOUNT", "headerName", "冻结金额", "width", 100, "sum", true, "valueFormatter", "currency"));
        tableHeader.add(MapUtil.mapper("field", "AMOUNTDEDUCTED", "headerName", "扣收后结余", "width", 100, "sum", true, "valueFormatter", "currency"));
        tableHeader.add(MapUtil.mapper("field", "START_DATE", "headerName", "费用期起", "width", 100));
        tableHeader.add(MapUtil.mapper("field", "END_DATE", "headerName", "费用期止", "width", 100));
        tableHeader.add(MapUtil.mapper("field", "SOURCE_BUSINESS_TYPE", "headerName", "源单据", "width", 90));
        tableHeader.add(MapUtil.mapper("field", "ORIGIN", "headerName", "源单号", "width", 100));
        tableHeader.add(MapUtil.mapper("field", "NOTE", "headerName", "备注", "width", 100));
        tableHeader.add(MapUtil.mapper("field", "CREATOR", "headerName", "创建人", "width", 100));
        tableHeader.add(MapUtil.mapper("field", "CREATE_DATE", "headerName", "创建时间", "width", 100));
        tableHeader.add(MapUtil.mapper("field", "SOURCE_BUSINESS_KEY", "headerName", "来源单据", "width", 100));
        tableHeader.add(MapUtil.mapper("field", "SOURCE", "headerName", "来源单号", "width", 100));

        JSONObject condition = request.get("condition");
        List<Map> filters = (List<Map>) condition.get("filters");
        JSONObject model = new JSONObject();
        filters.forEach(filter -> model.put((String) filter.get("field"), filter.get("value")));
        JSONObject node = ((JSONObject) request.get("data")).getJSONObject("node");
        model.put("DATE_OF_STATISTICS_STATE", node.get("DATE_OF_STATISTICS_STATE"));
        model.put("DATE_OF_STATISTICS_END", node.get("DATE_OF_STATISTICS_END"));
        JSONArray resultArray = merchantSettlementDao.merchantCostPlatform1(node);

        JSONObject result = new JSONObject();
        result.put("tableHeader", tableHeader);
        result.put("content", resultArray);
        return result;
    }
}
